function zero_num(mat=[]){
  var num = 0;
  for(var i=0;i<mat.length;i++){
    if(mat[i]==0) 
    num++;
    else 
    break
  }
  return num
}

function mat_sort(mat=[]){
  let mat_len = mat.length
  var sort = mat_len-1
  for(var i=0;i<mat_len-1;i++){
    for(var j=0;j<sort;j++){
      if(zero_num(mat[j])>zero_num(mat[j+1])){
        var m = mat[j].slice()
        mat[j] = mat[j+1].slice()
        mat[j+1] = m.slice()
      }
    }
    sort--
  }
  return mat
}

function mat_minus(mat_a=[],mat_b=[],coef){
  let len = mat_a.length
  var m = []
  for(var i=0;i<len;i++){
    m.push(mat_a[i] - coef*mat_b[i])
  }
  return m
}

function mat_transform(mat=[]){
  let mat_len = mat.length
  let size = mat[0].length
  for(var i=0;i<mat_len-1;i++){
    var m = mat_sort(mat);
    if(zero_num(m[i+1])>=size-1) break
    for(var j=i+1;j<mat_len;j++){
      if(zero_num(m[j])>=size-1 || zero_num(m[j])>zero_num(m[i])) break
      var n = zero_num(m[j])
      var m_a = mat_minus(m[j],m[i],parseFloat(m[j][n]/m[i][n]))
      m[j] = m_a.slice()
    }
  }
  return mat
}

function mat_R(mat=[]){
  for(var i=0;i<mat.length;i++){

  }
}

function mat_slove(mat=[]){
  var m = mat_transform(mat)
  var m_ = []
  var n = m[0].length - 1
  //得到系数矩阵
  for(var i=0;i<m.length;i++){
    m_.push(m[i].slice(0,m[i].length))
  }

  var r_m = 1
  var r_m_ = 1
  var size = m[0].length
  var index = []
  for(var j=1;j<m.length;j++){
    if(zero_num(m[j])==size) break

    if(zero_num(m[j])>zero_num(m[j-1])){
      r_m++
    }

    if(zero_num(m_[j])>zero_num(m_[j-1])){
      var num = zero_num(m_[j])-zero_num(m_[j-1])
      if(num>1){
        for(var k=0;k<num-1;k++){
          index.push(zero_num(m_[j])-1-i)
        }
      }
      r_m_++
    }
  }

  var s = []
  if(r_m_ == r_m && r_m==n){
    var sol = []
    var is = 0
    for(var i=n-1;i>=0;i--){
      if(sol.length>0){
        var sol_ = parseFloat(m[i][m[i].length-1])
        for(var j=0;j<sol.length;j++){
          sol_ -= parseFloat(m[i][m[i].length-2-j])*parseFloat(sol[j])
        }
        sol.push(parseFloat(sol_)/parseFloat(m[i][m[i].length-2-sol.length]))
      }
      else{
        sol.push(parseFloat(m[i][m[i].length-1]/m[i][m[i].length-2]))
      }
      if(isNaN(sol[n-1-i])){
        is=1
        break
      }
    }
    var slove
    if(is==1) slove = undefined
    else slove = sol.reverse()
  }
  else if(r_m_ == r_m && r_m<n){

  }
  else{
    
  }

  return slove
}

export {mat_slove}